package com.zendesk.maxwell.registry;

import com.zendesk.maxwell.MaxwellConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/12/13 15:52
 * @Description:
 */
public class ServiceRegistryManager {
	static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistryManager.class);

	private static volatile ServiceRegistryManager _instance;

	private IRegistryService registryService;

	public static ServiceRegistryManager getInstance(MaxwellConfig maxwellConfig) {
		if (_instance == null) {
			synchronized (ServiceRegistryManager.class) {
				if (_instance == null) {
					_instance = new ServiceRegistryManager(maxwellConfig);
				}
			}
		}
		return _instance;
	}

	public ServiceRegistryManager(MaxwellConfig maxwellConfig) {
		if (StringUtils.isBlank(maxwellConfig.registryType)) {
			this.registryService = new NoneRegistryService();
			return;
		}
		switch (maxwellConfig.registryType) {
			case "nacos":
				this.registryService = new NacosRegistryService(maxwellConfig);
				break;
			case "file":
				this.registryService = new FileRegistryService();
				break;
			default:
				break;
		}
	}

	/**
	 * 注册
	 * @author miaoguoxin
	 * @date 2021/12/22
	 */
	public void register(InetSocketAddress address) {
		try {
			this.registryService.register(address);
		} catch (Exception e) {
			LOGGER.error("注册服务异常:", e);
		}
	}

	/**
	 * 注销
	 * @author miaoguoxin
	 * @date 2021/12/22
	 */
	public void unregister(InetSocketAddress address) {
		try {
			this.registryService.unregister(address);
		} catch (Exception e) {
			LOGGER.error("注销服务异常:", e);
		}
	}
}
